package rpc_client

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/common/utils"
	"time"

	"git.myscrm.cn/golang/stark/v4"
	"git.myscrm.cn/golang/stark/v4/module/client_conn"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

//
// 获取rpc client对象
//
func GetClientConn(ctx context.Context, serviceName string) (*grpc.ClientConn, context.Context, error) {
	ctx, err := pairsMetaData(ctx, serviceName)
	if err != nil {
		return nil, ctx, err
	}

	conn, err := client_conn.NewConn(serviceName)
	if err != nil {
		return nil, ctx, err
	}

	clientConn, err := conn.GetAPMConn(ctx)
	if err != nil {
		return nil, ctx, err
	}

	return clientConn, ctx, nil
}

//
// 生成rpc签名字符串
//
func pairsMetaData(ctx context.Context, serviceName string) (context.Context, error) {
	appId := stark.Configer.(stark.ApolloConfigerIface).GetStringValue(serviceName+".appId", "")
	serect := stark.Configer.(stark.ApolloConfigerIface).GetStringValue(serviceName+".secret", "")
	if appId == "" || serect == "" {
		return ctx, errors.New("appid or serect is null")
	}

	var authInfo utils.AuthInfo
	authInfo.AppId = appId
	authInfo.TimeStamp = time.Now().Unix()
	str := fmt.Sprintf("%s&%d&%s", authInfo.AppId, authInfo.TimeStamp, serect)
	sign, err := utils.HmacSha256(str, serect)
	if err != nil {
		return ctx, err
	}
	a, err := json.Marshal(authInfo)
	if err != nil {
		return ctx, err
	}

	md := metadata.Pairs("authorization", "bearer "+fmt.Sprintf("%s.%s", sign, string(a)))
	ctx = metadata.NewOutgoingContext(context.Background(), md)

	return ctx, nil
}
